package com.dgshanger.sanhxiaofeisc.common;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;

import com.dgshanger.sanhxiaofeisc.R;

import org.greenrobot.eventbus.EventBus;

import cn.jpush.android.api.JPushInterface;

/**
 * JReceiver
 * 沉迷学习不能自拔
 * Describe：
 * Created by 雷小星🍀 on 2018/5/9 15:17.
 */

public class JReceiver extends BroadcastReceiver {
    private static final String TAG = "MyReceiver";

    private NotificationManager nm;
    private NotificationManager notifyManager;
    private NotificationCompat.Builder notifyBuilder;
    private Notification notification;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (null == nm) {
            nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        }
        Bundle bundle = intent.getExtras();
        if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            //处理自定义消息
            processCustomMessage(context, bundle);
        }
    }

    private void processCustomMessage(Context context, Bundle bundle) {
        notifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notifyBuilder = new NotificationCompat.Builder(context);

        String title = bundle.getString(JPushInterface.EXTRA_TITLE);
        String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);

        //自定义信息： 获取

        if (MyLifecycleHandler.isApplicationInForeground()) {
            //app在前台,不显示通知
            //显示小红点
            Constants.addUnReadMessage();
            EventBus.getDefault().post("showMessage");
        } else {
            //设置点击通知栏的动作为启动另外一个广播
//            Intent broadcastIntent = context.registerReceiver(new NotificationReceiver(), new IntentFilter(NotificationReceiver.ACTION_OPEN_NOTIFICAL));

            Intent broadcastIntent = new Intent("com.dgshanger.sanhxiaofeisc.NotificationReceiver");
            broadcastIntent.putExtra(JPushInterface.EXTRA_EXTRA, extras);

            PendingIntent pendingIntent = PendingIntent.
                    getBroadcast(context, 100, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);

            notifyBuilder.setContentTitle(title);
            notifyBuilder.setContentText(message);
            notifyBuilder.setContentIntent(pendingIntent);
            notifyBuilder.setAutoCancel(true);
            notifyBuilder.setSmallIcon(R.mipmap.ic_launcher);
            notification = notifyBuilder.build();
            notification.defaults |= Notification.DEFAULT_SOUND;
            notification.defaults |= Notification.DEFAULT_VIBRATE;
            notifyManager.notify(1000, notification);
        }
    }

}
